package ws

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func handler(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("Failed to upgrade connection to WebSocket:", err)
		return
	}
	defer conn.Close()

	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			fmt.Println("Failed to read message from WebSocket:", err)
			break
		}
		fmt.Println("Received message from WebSocket:", string(message))

		err = conn.WriteMessage(messageType, message)
		if err != nil {
			fmt.Println("Failed to write message to WebSocket:", err)
			break
		}
	}
}

func StartWS() {
	http.HandleFunc("/ws", handler)
	println("start....")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Failed to start WebSocket server:", err)
	}
}

// WSServer
type WSServer struct {
	connMap map[string]*websocket.Conn
}
